package com.snnsh.kjb.lottery.service;

import com.snnsh.kjb.lottery.dao.ILotteryRecordDao;
import com.snnsh.kjb.lottery.dao.IProductDao;
import com.snnsh.kjb.lottery.po.LotteryRecordPO;
import com.snnsh.kjb.lottery.po.ProductPO;
import com.snnsh.kjb.lottery.vo.ProductVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * packageName com.snnsh.kjb.lottery.service
 *
 * @author wick
 * @version V1.0.0
 * @date 2025/5/27
 */
@Service
public class LotteryRecordService {

    @Autowired
    private ILotteryRecordDao lotteryRecordDao;
    @Autowired
    private IProductDao productDao;
    
    /**
     * @description 查询所有的记录
     * @param prodName: 
     * @return List<LotteryRecordPO>
     * @author wick
     * @date 2025/5/27
     */
    public List<LotteryRecordPO> list(String prodName) {
        List<LotteryRecordPO> list = lotteryRecordDao.list(prodName);
        return list;
    }
    /**
     * @description 抽奖
     * @param : 
     * @return ProductVO
     * @author wick
     * @date 2025/5/28
     */
    public ProductVO lotteryProduct(){
        //抽奖
        Map<String,Object> params = new HashMap<>();
        params.put("lotteryFlag",true);
        List<ProductPO> list = productDao.list(params);
        if(CollectionUtils.isEmpty(list)){
            throw new RuntimeException("没有剩余的奖品");
        }
        //得到抽奖的产品
        ProductPO productPO = lotteryProductByProductList(list);
        //保存记录
        saveLotteryRecord(productPO);

        productPO.setLeftAmount(productPO.getLeftAmount() -1);
        productDao.updateProduct(productPO);
        //保存
        return productPO.toVo();
    }
    /**
     * @description 抽奖
     * @param list:
     * @return ProductPO
     * @author wick
     * @date 2025/5/29
     */
    private ProductPO lotteryProductByProductList(List<ProductPO> list) {
        //得到
        int allWeight = 0;
        for (ProductPO productPO : list) {
            allWeight += productPO.getWeight();
        }
        ArrayList<ProductPO> weightList = new ArrayList<>(allWeight);
        for (ProductPO productPO : list) {
            for (int i = 0; i < productPO.getWeight(); i++) {
                weightList.add(productPO);
            }
        }
        //得到奖品
        Random random = new Random();
        int i = random.nextInt(weightList.size());
        ProductPO productPO = weightList.get(i);
        return productPO;
    }

    public void saveLotteryRecord(ProductPO productPO) {
        lotteryRecordDao.addLotteryRecord(productPO);
    }

    public void clearRecord() {
        lotteryRecordDao.clearLotteryRecord();
    }
}
